//=========================================================================
// Copyright (C) 2024 The C++ Component Model(COMO) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================

#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <linux/sched/types.h>
#include <linux/sched.h>
#include <sys/types.h>
#include <string.h>
#include <syslog.h>

int sched_setattr(pid_t pid, const struct sched_attr *attr, unsigned int flags)
{
   return syscall(__NR_sched_setattr, pid, attr, flags);
}

/**
 * http://www.wowotech.net/process_management/deadline-scheduler-1.html
 * 如果对实时任务进行抽象，那么它需要三个元素：周期（period），运行时间（runtime）和最
 * 后期限（deadline）。Deadline调度器正是利用了这一点（指对实时任务完美的抽象），允许用
 * 户来指定该任务的具体需求，从而使系统能够做出最好的调度决策，即使在负载很高的系统中也
 * 能保证实时任务的调度。
 */
int voter_sched_setattr()
{
    struct sched_attr attr;

    memset(&attr, 0, sizeof(attr));
    attr.size = sizeof(attr);
    attr.sched_policy = SCHED_DEADLINE;

    // 设置计算时间、截止时间和周期
    attr.sched_runtime = 500000000;   // 500 ms
    attr.sched_deadline = 1000000000; //   1  s
    attr.sched_period = 1000000000;   //   1  s

    /**
     * sched_setattr()系统调用为ID在pid中指定的线程设置调度策略和相关属性。如果pid等
     * 于零，则将设置调度策略和调用线程的属性。
     */
    if (sched_setattr(0, &attr, 0) == -1) {
        syslog(LOG_ERR, "sched_setattr error\n");
        return -1;
    }

    return 0;
}
